<?php
namespace App\Handlers;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class ImageUploadHandler{
    protected $allowed_ext = ['png','git','jpg','jpeg'];

    public function save($file,$folder,$model_id,$max_width=false,$unlink=false){
        //文件夹路径
        $folder_name = "uploads/images/$folder/".date('Ym/d',time());
        //物理的文件夹路径
        $upload_path = public_path().'/'."$folder_name";
        //后缀
        $extension = strtolower($file->getClientOriginalExtension()) ?: 'png';
        //设置图片名称
        $filename = md5($model_id.time()).'.'.$extension;
        //判断
        if(!in_array($extension,$this->allowed_ext)){
            return false;
        }
        $file->move($upload_path,$filename);
        //缩放图片
        if($max_width && $extension != 'gif'){
            $this->reduceSize($upload_path.'/'.$filename,$max_width);
        }
        //删除旧的图片
        if($unlink){
            $this->delOldImage($model_id);
        }
        return [
          'path'=>config('app.url')."/$folder_name/$filename"
        ];
    }
    public function reduceSize($file_path,$max_width){
        $image = Image::make($file_path);
        $image->resize($max_width,null,function ($obj){
            //等比例缩放
            $obj->aspectRatio();
            //不扩大
            $obj->upsize();
        });
        $image->save();
    }
    public function delOldImage($user_id){
        $user = DB::table('users')->find($user_id);
        if($user){
            $user_avatar = $user->avatar;
            $pic_arr = explode('/',$user_avatar);
            $path_arr = array_slice($pic_arr,3,5);
            $folder_path = implode('/',$path_arr);
            //旧的图片文件名
            $old_file_name = array_pop($pic_arr);
            $real_path = public_path().'/'.$folder_path.'/'.$old_file_name;
            @unlink($real_path);
        }
    }
}
